﻿using System;
using Bosphorus.Migrator.Dialect.Core;
using Bosphorus.Migrator.Model;
using Bosphorus.Migrator.Core.MigrationCommand;
using System.Text;
using System.Data;

namespace Bosphorus.Migrator.Dialect.DummyImplementation
{
    public class ColumnDialect : AbstractDialect<AbstractCommand<Column>>
    {
        public override string Create(AbstractCommand<Column> command)
        {
            Column column = command.Model;

            string columnName = AddColumnName(column.Name);
            string columnType = AddColumnType(column.DataType);
            string columnSize = AddColumnSize(column.Size);
            string columnNullable = AddColumnNullable(column.Nullable);

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(columnName);
            stringBuilder.Append(columnType);
            stringBuilder.Append(columnSize);
            stringBuilder.Append(columnNullable);

            return stringBuilder.ToString();
        }

        public override string Alter(AbstractCommand<Column> command)
        {
            Column column = command.Model;

            string columnName = AddColumnName(column.Name);
            string columnType = AddColumnType(column.DataType);
            string columnSize = AddColumnSize(column.Size);
            string columnNullable = AddColumnNullable(column.Nullable);

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(columnName);
            stringBuilder.Append(columnType);
            stringBuilder.Append(columnSize);
            stringBuilder.Append(columnNullable);

            return stringBuilder.ToString();
        }

        public override string Drop(AbstractCommand<Column> command)
        {
            Column column = command.Model;

            string columnName = AddColumnName(column.Name);

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(columnName);

            return stringBuilder.ToString();
        }

        private string AddColumnName(string name)
        {
            return string.Format(" [{0}]", name);
        }

        private string AddColumnType(SqlDbType sqlDbType)
        {
            return string.Format(" [{0}]", sqlDbType);
        }

        private string AddColumnSize(int size)
        {
            if(size == default(int))
            {
                return string.Empty;
            }

            return string.Format("({0})", size);
        }

        private string AddColumnNullable(bool nullable)
        {
            string nullableString = string.Empty;
            if (!nullable)
            {
                nullableString += " NOT";
            }

            nullableString += " NULL";
            return nullableString;
        }
    }
}